package com.ml4ai.backend.services.impl;

import com.ml4ai.backend.consts.Const;
import com.ml4ai.backend.services.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by uesr on 2018/9/16.
 */
@Component
public class CacheServiceImpl implements CacheService {

    @Autowired
    RedisTemplate redisTemplate;

    private Map<String, Map<String, Object>> cache = new LinkedHashMap<>();

    private Map<String, Object> attach(String hash) {
        Map<String, Object> store = cache.get(hash);
        if (store == null) {
            store = new LinkedHashMap<>();
        }
        cache.put(hash, store);
        return store;
    }

    @Override
    public void put(String hash, String key, Object value) {
        /*
        Map<String, Object> hashMap = attach(hash);
        hashMap.put(key, value);
        */
        HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
        hashOperations.put(hash, key, value);
    }

    @Override
    public Object get(String hash, String key) {
        /*
        Map<String, Object> hashMap = attach(hash);
        return hashMap.get(key);
        */
        HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
        return hashOperations.get(hash, key);
    }

    @Override
    public void delete(String hash, String key) {
        /*
        Map<String, Object> hashMap = attach(hash);
        hashMap.remove(key);
        */
        HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(hash, key);
    }

    @Override
    public void push(Object innerMessage) {
        redisTemplate.convertAndSend(Const.PUBLIC_MESSAGE, innerMessage);
    }
}
